<template>
  <div class="list-page">
    <EmergencyVerticalTabNav />
    <div class="content-container">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <div>
              <el-form-item label="队伍名称" prop="teamName">
                <el-input v-model="queryParams.teamName" placeholder="请输入队伍名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="队伍类型" prop="teamType">
                <el-select v-model="queryParams.teamType" placeholder="请选择队伍类型" clearable style="width: 180px">
                  <el-option label="消防救援" :value="1" />
                  <el-option label="医疗救护" :value="2" />
                  <el-option label="工程救援" :value="3" />
                  <el-option label="水上救援" :value="4" />
                  <el-option label="山地救援" :value="5" />
                  <el-option label="其他" :value="6" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </div>
            <div>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" class="add-button" @click="handleAdd">新增</el-button>
            </div>
          </el-form>
        </el-card>
      </div>

      <!-- 列表区域 -->
      <el-card shadow="hover" class="w-full">
        <el-table
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="teamName" label="队伍名称" min-width="150" />
          <el-table-column prop="teamType" label="队伍类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTeamTypeTag(row.teamType)">
                {{ getTeamTypeName(row.teamType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="memberCount" label="人员数量" width="100" align="center" />
          <el-table-column prop="specialties" label="专业特长" min-width="150" />
          <el-table-column prop="equipments" label="主要装备" min-width="150" />
          <el-table-column prop="contactPerson" label="联系人" width="120" />
          <el-table-column prop="contactPhone" label="联系电话" width="150" />
          <el-table-column prop="location" label="驻地" min-width="150" />
          <el-table-column prop="responseTime" label="响应时间" width="120">
            <template #default="{ row }">
              {{ row.responseTime }}分钟
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusTag(row.status)">
                {{ getStatusName(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            background
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        center
        destroy-on-close
        class="custom-dialog"
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">{{ dialogTitle }}</span>
          </div>
        </template>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="队伍名称" prop="teamName">
            <el-input v-model="form.teamName" placeholder="请输入队伍名称" />
          </el-form-item>
          <el-form-item label="队伍类型" prop="teamType">
            <el-select v-model="form.teamType" placeholder="请选择队伍类型" style="width: 100%">
              <el-option label="消防救援" :value="1" />
              <el-option label="医疗救护" :value="2" />
              <el-option label="工程救援" :value="3" />
              <el-option label="水上救援" :value="4" />
              <el-option label="山地救援" :value="5" />
              <el-option label="其他" :value="6" />
            </el-select>
          </el-form-item>
          <el-form-item label="人员数量" prop="memberCount">
            <el-input-number v-model="form.memberCount" :min="1" style="width: 100%" />
          </el-form-item>
          <el-form-item label="专业特长" prop="specialties">
            <el-input v-model="form.specialties" placeholder="请输入专业特长" />
          </el-form-item>
          <el-form-item label="主要装备" prop="equipments">
            <el-input v-model="form.equipments" placeholder="请输入主要装备" />
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="驻地" prop="location">
            <el-input v-model="form.location" placeholder="请输入驻地" />
          </el-form-item>
          <el-form-item label="响应时间" prop="responseTime">
            <el-input-number v-model="form.responseTime" :min="1" style="width: 100%">
              <template #suffix>分钟</template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">待命</el-radio>
              <el-radio :label="2">出动</el-radio>
              <el-radio :label="3">训练</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { Plus, Search, RefreshRight } from '@element-plus/icons-vue';
import { 
  getRescueTeamList, 
  getRescueTeamDetail, 
  addRescueTeam, 
  updateRescueTeam, 
  deleteRescueTeam 
} from '@/api/bridge/command/recue';
import EmergencyVerticalTabNav from "./components/EmergencyVerticalTabNav.vue";

// 路由
const router = useRouter();

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);
const queryFormRef = ref();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  teamName: '',
  teamType: null
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form = ref({
  id: null,
  teamName: "",
  teamType: 1,
  memberCount: 1,
  specialties: "",
  equipments: "",
  contactPerson: "",
  contactPhone: "",
  location: "",
  responseTime: 30,
  status: 1
});

// 表单验证规则
const rules = {
  teamName: [
    { required: true, message: "请输入队伍名称", trigger: "blur" }
  ],
  teamType: [
    { required: true, message: "请选择队伍类型", trigger: "change" }
  ],
  memberCount: [
    { required: true, message: "请输入人员数量", trigger: "blur" }
  ],
  contactPerson: [
    { required: true, message: "请输入联系人", trigger: "blur" }
  ],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  location: [
    { required: true, message: "请输入驻地", trigger: "blur" }
  ],
  responseTime: [
    { required: true, message: "请输入响应时间", trigger: "blur" }
  ],
  status: [
    { required: true, message: "请选择状态", trigger: "change" }
  ]
};

// 获取队伍类型名称
const getTeamTypeName = (type) => {
  const typeMap = {
    1: "消防救援",
    2: "医疗救护",
    3: "工程救援",
    4: "水上救援",
    5: "山地救援",
    6: "其他"
  };
  return typeMap[type] || "未知";
};

// 获取队伍类型标签样式
const getTeamTypeTag = (type) => {
  const typeMap = {
    1: "danger",   // 消防救援 - 红色
    2: "success",  // 医疗救护 - 绿色
    3: "warning",  // 工程救援 - 黄色
    4: "info",     // 水上救援 - 灰色
    5: "primary",  // 山地救援 - 蓝色
    6: ""          // 其他 - 默认
  };
  return typeMap[type] || "";
};

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    1: "待命",
    2: "出动",
    3: "训练"
  };
  return statusMap[status] || "未知";
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    1: "success",  // 待命 - 绿色
    2: "danger",   // 出动 - 红色
    3: "warning"   // 训练 - 黄色
  };
  return statusMap[status] || "";
};

// 获取救援队伍列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getRescueTeamList({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      teamName: queryParams.teamName,
      teamType: queryParams.teamType
    });
    tableData.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error("获取救援队伍列表失败", error);
    ElMessage.error("获取救援队伍列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.teamName = '';
  queryParams.teamType = null;
  handleQuery();
};

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = "新增救援队伍";
  form.value = {
    id: null,
    teamName: "",
    teamType: 1,
    memberCount: 1,
    specialties: "",
    equipments: "",
    contactPerson: "",
    contactPhone: "",
    location: "",
    responseTime: 30,
    status: 1
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  dialogTitle.value = "编辑救援队伍";
  try {
    const res = await getRescueTeamDetail(row.id);
    form.value = res.data;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取救援队伍详情失败", error);
    ElMessage.error("获取救援队伍详情失败");
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除救援队伍"${row.teamName}"吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await deleteRescueTeam(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除救援队伍失败", error);
      ElMessage.error("删除救援队伍失败");
    }
  }).catch(() => {
    // 取消删除
  });
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.id) {
          // 编辑
          await updateRescueTeam(form.value);
          ElMessage.success("更新成功");
        } else {
          // 新增
          await addRescueTeam(form.value);
          ElMessage.success("新增成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("操作失败", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  queryParams.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryParams.pageNum = val;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
$bg-color-page: var(--el-bg-color-page);
$bg-color-overlay: var(--el-bg-color-overlay);
$box-shadow-light: var(--el-box-shadow-light);
$box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
$border-radius: 4px;
$border-radius-dialog: 8px;
$border-color-light: var(--el-border-color-light);
$color-primary: var(--el-color-primary);
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$deep-box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
$header-padding: 15px 20px;
$general-padding: 20px;
$footer-padding: 10px 20px;
$divider-color: #f0f0f0;

.list-page {
  padding: 20px;
  background: $bg-color-page;
  border-radius: $border-radius;
  box-shadow: $box-shadow-light;
  display: flex;
  gap: 20px;
}

.content-container {
  flex: 1;
  overflow: hidden;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  background: $bg-color-overlay;
  padding: 16px;
  border-radius: $border-radius;
}

.search-input {
  width: 300px;
  margin-left: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: $bg-color-overlay;

  :deep(th) {
    background: $bg-color-page !important;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: $bg-color-page;
  border-radius: $border-radius-dialog $border-radius-dialog 0 0;
  border-bottom: 1px solid $border-color-light;

  .dialog-title {
    font-size: 18px;
    color: #303133;
    font-weight: 600;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.btn-group {
  .edit-btn,
  .cancel-btn,
  .save-btn {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 10px 20px;
    border-radius: 6px;
  }

  .edit-btn {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .cancel-btn {
    &:hover {
      background-color: #f4f4f5;
      color: #909399;
    }
  }

  .save-btn {
    padding: 10px 24px;

    &:hover {
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    }
  }
}

.disabled-field {
  :deep(.el-input__inner) {
    background-color: #f8f9fa;
    border-color: #e4e7ed;
    color: #909399;
    cursor: not-allowed;
  }
}

.error-message {
  color: red;
  font-size: 14px;
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: $border-radius-dialog;
    box-shadow: $box-shadow;

    .el-dialog__body {
      padding: 24px;
      background: $bg-color-overlay;
    }

    .el-dialog__header {
      padding: 0;
      margin: 0;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #303133;
        font-size: 24px;
        z-index: 1000;

        &:hover {
          color: $color-primary;
        }
      }
    }

    .el-dialog__footer {
      padding: 10px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.dialog-form {
  :deep(.el-form-item__label) {
    color: var(--el-text-color-regular);
  }

  :deep(.el-input__inner) {
    background-color: var(--el-bg-color-overlay);
    border-color: var(--el-border-color);
    color: var(--el-text-color-primary);
  }
}
</style> 